#!/usr/bin/env lua
-- Lua Battle System - 代码质量审计器
-- 提供全面的代码质量评估、静态分析和质量指标计算
-- 设置Lua路径
package.path = package.path .. ';src/?.lua;src/utils/?.lua;src/config/?.lua;tests/?.lua;tests/unit/?.lua'

local Logger = require("utils.logger")
local TableUtils = require("utils.table_utils")

local CodeQualityAuditor = {
    -- 审计器配置
    config = {
        -- 质量标准
        quality_standards = {
            -- 代码复杂度阈值
            max_cyclomatic_complexity = 10,
            max_function_length = 50,
            max_file_length = 500,

            -- 命名规范
            naming_conventions = {
                snake_case_variables = true,
                snake_case_functions = true,
                pascal_case_classes = true,
                upper_case_constants = true
            },

            -- 文档标准
            documentation_requirements = {
                function_comments = true,
                class_comments = true,
                module_comments = true,
                inline_comments_threshold = 0.3
            }
        },

        -- 审计范围
        audit_scope = {
            include_patterns = {
                "src/**/*.lua",
                "tests/**/*.lua"
            },
            exclude_patterns = {
                "src/example_battle.lua",
                "tests/test_helpers.lua"
            }
        }
    },

    -- 审计状态
    state = {
        current_audit = nil,
        results = {},
        metrics = {},
        issues = {}
    }
}

-- 初始化审计器
function CodeQualityAuditor:init(config)
    Logger.info("初始化代码质量审计器", {
        version = "1.0",
        scope = "全面代码质量评估"
    })

    if config then
        TableUtils.merge(self.config, config)
    end

    self.state.current_audit = {
        start_time = os.time(),
        files_audited = 0,
        total_issues = 0,
        quality_score = 0
    }

    Logger.info("代码质量审计器初始化完成", {
        quality_standards = self.config.quality_standards,
        audit_scope = self.config.audit_scope
    })
end

-- 执行全面代码质量审计
function CodeQualityAuditor:perform_full_audit()
    if not self.state.current_audit then
        error("审计器未初始化，请先调用init()")
    end

    Logger.info("开始全面代码质量审计")

    local audit_results = {
        summary = {
            total_files = 0,
            files_passed = 0,
            files_failed = 0,
            overall_quality_score = 0,
            audit_timestamp = os.date("%Y-%m-%d %H:%M:%S")
        },
        file_metrics = {},
        quality_issues = {},
        recommendations = {}
    }

    -- 获取所有需要审计的文件
    local files_to_audit = self:get_files_to_audit()
    audit_results.summary.total_files = #files_to_audit

    Logger.info("开始审计文件", {file_count = #files_to_audit})

    -- 逐个文件进行审计
    for i, file_path in ipairs(files_to_audit) do
        Logger.debug("审计文件", {
            file_index = i,
            total_files = #files_to_audit,
            current_file = file_path
        })

        local file_result = self:audit_file(file_path)
        audit_results.file_metrics[file_path] = file_result

        if file_result.quality_score >= 80 then
            audit_results.summary.files_passed = audit_results.summary.files_passed + 1
        else
            audit_results.summary.files_failed = audit_results.summary.files_failed + 1
        end

        -- 收集质量问题
        for _, issue in ipairs(file_result.issues) do
            table.insert(audit_results.quality_issues, {
                file = file_path,
                type = issue.type,
                severity = issue.severity,
                message = issue.message,
                line = issue.line
            })
        end
    end

    -- 计算总体质量评分
    audit_results.summary.overall_quality_score = self:calculate_overall_quality_score(audit_results)

    -- 生成改进建议
    audit_results.recommendations = self:generate_recommendations(audit_results)

    -- 更新审计状态
    self.state.current_audit.files_audited = #files_to_audit
    self.state.current_audit.total_issues = #audit_results.quality_issues
    self.state.current_audit.quality_score = audit_results.summary.overall_quality_score

    Logger.info("全面代码质量审计完成", {
        files_audited = #files_to_audit,
        total_issues = #audit_results.quality_issues,
        overall_quality_score = audit_results.summary.overall_quality_score
    })

    return audit_results
end

-- 审计单个文件
function CodeQualityAuditor:audit_file(file_path)
    local file_result = {
        file_path = file_path,
        quality_score = 0,
        metrics = {},
        issues = {},
        complexity_analysis = {},
        documentation_analysis = {},
        naming_analysis = {}
    }

    -- 读取文件内容
    local file_content = self:read_file(file_path)
    if not file_content then
        table.insert(file_result.issues, {
            type = "file_error",
            severity = "critical",
            message = "无法读取文件",
            line = 0
        })
        return file_result
    end

    -- 执行各种质量检查
    file_result.metrics = self:calculate_file_metrics(file_content)
    file_result.complexity_analysis = self:analyze_complexity(file_content)
    file_result.documentation_analysis = self:analyze_documentation(file_content)
    file_result.naming_analysis = self:analyze_naming_conventions(file_content)

    -- 检查代码规范
    self:check_coding_standards(file_content, file_result)

    -- 检查潜在问题
    self:check_potential_issues(file_content, file_result)

    -- 计算文件质量评分
    file_result.quality_score = self:calculate_file_quality_score(file_result)

    -- 收集所有问题
    for _, issue in ipairs(file_result.complexity_analysis.issues or {}) do
        table.insert(file_result.issues, issue)
    end
    for _, issue in ipairs(file_result.documentation_analysis.issues or {}) do
        table.insert(file_result.issues, issue)
    end
    for _, issue in ipairs(file_result.naming_analysis.issues or {}) do
        table.insert(file_result.issues, issue)
    end

    return file_result
end

-- 计算文件基本指标
function CodeQualityAuditor:calculate_file_metrics(file_content)
    local lines = {}
    for line in file_content:gmatch("[^\r\n]+") do
        table.insert(lines, line)
    end

    local metrics = {
        total_lines = #lines,
        code_lines = 0,
        comment_lines = 0,
        blank_lines = 0,
        functions = 0,
        local_variables = 0,
        global_variables = 0,
        require_statements = 0
    }

    local in_multiline_comment = false

    for _, line in ipairs(lines) do
        local trimmed = line:match("^%s*(.-)%s*$")

        -- 跳过空行
        if trimmed == "" then
            metrics.blank_lines = metrics.blank_lines + 1
        elseif trimmed:match("^%-%-") then
            metrics.comment_lines = metrics.comment_lines + 1
        elseif trimmed:match("^%-%[%[") then
            in_multiline_comment = true
            metrics.comment_lines = metrics.comment_lines + 1
        elseif trimmed:match("^%]%]") then
            in_multiline_comment = false
            metrics.comment_lines = metrics.comment_lines + 1
        elseif in_multiline_comment then
            metrics.comment_lines = metrics.comment_lines + 1
        else
            metrics.code_lines = metrics.code_lines + 1

            -- 统计代码元素
            if trimmed:match("^function%s+") or trimmed:match("function%s+.*%(") then
                metrics.functions = metrics.functions + 1
            end
            if trimmed:match("^local%s+") then
                metrics.local_variables = metrics.local_variables + 1
            end
            if trimmed:match("^require%s*%(") then
                metrics.require_statements = metrics.require_statements + 1
            end
            if trimmed:match("%w+%s*=") and not trimmed:match("^local%s+") then
                metrics.global_variables = metrics.global_variables + 1
            end
        end
    end

    -- 计算密度指标
    metrics.comment_density = metrics.total_lines > 0 and
        (metrics.comment_lines / metrics.total_lines) or 0
    metrics.code_density = metrics.total_lines > 0 and
        (metrics.code_lines / metrics.total_lines) or 0

    return metrics
end

-- 分析代码复杂度
function CodeQualityAuditor:analyze_complexity(file_content)
    local analysis = {
        cyclomatic_complexity = 1,
        max_nesting_level = 0,
        long_functions = {},
        complex_functions = {},
        issues = {}
    }

    local lines = {}
    for line in file_content:gmatch("[^\r\n]+") do
        table.insert(lines, line)
    end

    local current_function = nil
    local current_function_start = 0
    local current_function_complexity = 1
    local nesting_level = 0

    for i, line in ipairs(lines) do
        local trimmed = line:match("^%s*(.-)%s*$")

        -- 检测函数开始
        local function_name = trimmed:match("^function%s+(%w+%.?%w*)")
        if not function_name then
            function_name = trimmed:match("function%s+(%w+%.?%w*)")
        end

        if function_name then
            -- 保存前一个函数的信息
            if current_function then
                local func_info = {
                    name = current_function,
                    start_line = current_function_start,
                    end_line = i - 1,
                    length = i - 1 - current_function_start + 1,
                    complexity = current_function_complexity
                }

                -- 检查函数长度
                if func_info.length > self.config.quality_standards.max_function_length then
                    table.insert(analysis.long_functions, func_info)
                    table.insert(analysis.issues, {
                        type = "long_function",
                        severity = "warning",
                        message = string.format("函数 '%s' 过长 (%d 行)",
                            func_info.name, func_info.length),
                        line = func_info.start_line
                    })
                end

                -- 检查函数复杂度
                if func_info.complexity > self.config.quality_standards.max_cyclomatic_complexity then
                    table.insert(analysis.complex_functions, func_info)
                    table.insert(analysis.issues, {
                        type = "high_complexity",
                        severity = "warning",
                        message = string.format("函数 '%s' 复杂度过高 (%d)",
                            func_info.name, func_info.complexity),
                        line = func_info.start_line
                    })
                end
            end

            -- 开始新函数
            current_function = function_name
            current_function_start = i
            current_function_complexity = 1
        end

        -- 计算圈复杂度
        if current_function then
            if trimmed:match("%bif%s+then") or trimmed:match("^if%s+then") then
                current_function_complexity = current_function_complexity + 1
                nesting_level = nesting_level + 1
                analysis.max_nesting_level = math.max(analysis.max_nesting_level, nesting_level)
            elseif trimmed:match("for%s+") or trimmed:match("while%s+") then
                current_function_complexity = current_function_complexity + 1
                nesting_level = nesting_level + 1
                analysis.max_nesting_level = math.max(analysis.max_nesting_level, nesting_level)
            elseif trimmed:match("elseif%s+then") then
                current_function_complexity = current_function_complexity + 1
            elseif trimmed:match("else") then
                -- else 不增加复杂度
            elseif trimmed:match("end") then
                nesting_level = math.max(0, nesting_level - 1)
            end
        end
    end

    -- 处理最后一个函数
    if current_function then
        local func_info = {
            name = current_function,
            start_line = current_function_start,
            end_line = #lines,
            length = #lines - current_function_start + 1,
            complexity = current_function_complexity
        }

        if func_info.length > self.config.quality_standards.max_function_length then
            table.insert(analysis.long_functions, func_info)
        end
        if func_info.complexity > self.config.quality_standards.max_cyclomatic_complexity then
            table.insert(analysis.complex_functions, func_info)
        end
    end

    analysis.cyclomatic_complexity = current_function_complexity

    return analysis
end

-- 分析文档质量
function CodeQualityAuditor:analyze_documentation(file_content)
    local analysis = {
        has_module_comment = false,
        has_function_comments = {},
        comment_density = 0,
        documented_functions = 0,
        total_functions = 0,
        issues = {}
    }

    local lines = {}
    for line in file_content:gmatch("[^\r\n]+") do
        table.insert(lines, line)
    end

    local comment_lines = 0
    local in_multiline_comment = false
    local current_function_documented = false

    for i, line in ipairs(lines) do
        local trimmed = line:match("^%s*(.-)%s*$")

        -- 检查模块注释
        if i <= 5 and (trimmed:match("^%-%-") or trimmed:match("^%-%[%[")) then
            analysis.has_module_comment = true
        end

        -- 统计注释行
        if trimmed:match("^%-%-") then
            comment_lines = comment_lines + 1
            if current_function_documented == false then
                current_function_documented = true
            end
        elseif trimmed:match("^%-%[%[") then
            in_multiline_comment = true
            comment_lines = comment_lines + 1
        elseif trimmed:match("^%]%]") then
            in_multiline_comment = false
            comment_lines = comment_lines + 1
        elseif in_multiline_comment then
            comment_lines = comment_lines + 1
        elseif trimmed:match("^function%s+") or trimmed:match("function%s+.*%(") then
            analysis.total_functions = analysis.total_functions + 1
            if current_function_documented then
                analysis.documented_functions = analysis.documented_functions + 1
                current_function_documented = false
            end
        end
    end

    analysis.comment_density = #lines > 0 and (comment_lines / #lines) or 0

    -- 检查文档问题
    if not analysis.has_module_comment then
        table.insert(analysis.issues, {
            type = "missing_module_doc",
            severity = "info",
            message = "缺少模块级文档注释",
            line = 1
        })
    end

    local doc_coverage = analysis.total_functions > 0 and
        (analysis.documented_functions / analysis.total_functions) or 0

    if doc_coverage < 0.5 then
        table.insert(analysis.issues, {
            type = "low_documentation",
            severity = "warning",
            message = string.format("函数文档覆盖率过低 (%.1f%%)", doc_coverage * 100),
            line = 0
        })
    end

    return analysis
end

-- 分析命名规范
function CodeQualityAuditor:analyze_naming_conventions(file_content)
    local analysis = {
        snake_case_violations = {},
        pascal_case_violations = {},
        naming_issues = {},
        issues = {}
    }

    local lines = {}
    for line in file_content:gmatch("[^\r\n]+") do
        table.insert(lines, line)
    end

    for i, line in ipairs(lines) do
        local trimmed = line:match("^%s*(.-)%s*$")

        -- 检查变量命名（蛇形命名法）
        local var_name = trimmed:match("^local%s+([a-z][a-zA-Z0-9_]*)%s*=")
        if var_name then
            if not var_name:match("^[a-z][a-z0-9_]*$") then
                table.insert(analysis.snake_case_violations, {
                    name = var_name,
                    line = i,
                    type = "variable"
                })
                table.insert(analysis.issues, {
                    type = "naming_convention",
                    severity = "info",
                    message = string.format("变量 '%s' 应使用蛇形命名法", var_name),
                    line = i
                })
            end
        end

        -- 检查函数命名（蛇形命名法）
        local func_name = trimmed:match("^function%s+([a-z][a-zA-Z0-9_]*)")
        if func_name then
            if not func_name:match("^[a-z][a-z0-9_]*$") then
                table.insert(analysis.snake_case_violations, {
                    name = func_name,
                    line = i,
                    type = "function"
                })
                table.insert(analysis.issues, {
                    type = "naming_convention",
                    severity = "info",
                    message = string.format("函数 '%s' 应使用蛇形命名法", func_name),
                    line = i
                })
            end
        end

        -- 检查类命名（帕斯卡命名法）
        local class_name = trimmed:match("([A-Z][a-zA-Z0-9]*)%s*=")
        if class_name and trimmed:match("^local") then
            if not class_name:match("^[A-Z][a-zA-Z0-9]*$") then
                table.insert(analysis.pascal_case_violations, {
                    name = class_name,
                    line = i
                })
                table.insert(analysis.issues, {
                    type = "naming_convention",
                    severity = "info",
                    message = string.format("类 '%s' 应使用帕斯卡命名法", class_name),
                    line = i
                })
            end
        end
    end

    return analysis
end

-- 检查编码标准
function CodeQualityAuditor:check_coding_standards(file_content, file_result)
    local lines = {}
    for line in file_content:gmatch("[^\r\n]+") do
        table.insert(lines, line)
    end

    for i, line in ipairs(lines) do
        local trimmed = line:match("^%s*(.-)%s*$")

        -- 检查制表符使用（应该使用空格）
        if line:match("\t") then
            table.insert(file_result.issues, {
                type = "formatting",
                severity = "info",
                message = "应使用空格而不是制表符进行缩进",
                line = i
            })
        end

        -- 检查行长度
        if #line > 120 then
            table.insert(file_result.issues, {
                type = "line_length",
                severity = "info",
                message = string.format("行过长 (%d 字符)", #line),
                line = i
            })
        end

        -- 检查全局变量使用
        if trimmed:match("^[^%-%-]*%w+%s*=") and not trimmed:match("^local") then
            table.insert(file_result.issues, {
                type = "global_variable",
                severity = "warning",
                message = "建议使用 local 声明变量以避免全局污染",
                line = i
            })
        end
    end
end

-- 检查潜在问题
function CodeQualityAuditor:check_potential_issues(file_content, file_result)
    local lines = {}
    for line in file_content:gmatch("[^\r\n]+") do
        table.insert(lines, line)
    end

    for i, line in ipairs(lines) do
        local trimmed = line:match("^%s*(.-)%s*$")

        -- 检查未使用的变量
        if trimmed:match("^local%s+.*unused") then
            table.insert(file_result.issues, {
                type = "unused_variable",
                severity = "warning",
                message = "检测到可能未使用的变量",
                line = i
            })
        end

        -- 检查TODO/FIXME注释
        if trimmed:match("TODO") or trimmed:match("FIXME") then
            table.insert(file_result.issues, {
                type = "todo_comment",
                severity = "info",
                message = "存在待办事项注释",
                line = i
            })
        end

        -- 检查调试代码
        if trimmed:match("print%(") then
            table.insert(file_result.issues, {
                type = "debug_code",
                severity = "info",
                message = "存在调试代码",
                line = i
            })
        end
    end
end

-- 计算文件质量评分
function CodeQualityAuditor:calculate_file_quality_score(file_result)
    local score = 100

    -- 复杂度扣分
    for _, func in ipairs(file_result.complexity_analysis.long_functions or {}) do
        score = score - math.min(20, func.length / 10)
    end

    for _, func in ipairs(file_result.complexity_analysis.complex_functions or {}) do
        score = score - math.min(30, func.complexity * 2)
    end

    -- 文档扣分
    if not file_result.documentation_analysis.has_module_comment then
        score = score - 10
    end

    local doc_coverage = file_result.documentation_analysis.total_functions > 0 and
        (file_result.documentation_analysis.documented_functions / file_result.documentation_analysis.total_functions) or 0

    if doc_coverage < 0.5 then
        score = score - (0.5 - doc_coverage) * 40
    end

    -- 命名规范扣分
    local naming_violations = #file_result.naming_analysis.snake_case_violations +
                            #file_result.naming_analysis.pascal_case_violations
    score = score - math.min(20, naming_violations * 2)

    -- 其他问题扣分
    local critical_issues = 0
    local warning_issues = 0
    local info_issues = 0

    for _, issue in ipairs(file_result.issues) do
        if issue.severity == "critical" then
            critical_issues = critical_issues + 1
        elseif issue.severity == "warning" then
            warning_issues = warning_issues + 1
        else
            info_issues = info_issues + 1
        end
    end

    score = score - critical_issues * 25 - warning_issues * 10 - info_issues * 2

    return math.max(0, math.min(100, score))
end

-- 计算总体质量评分
function CodeQualityAuditor:calculate_overall_quality_score(audit_results)
    local total_score = 0
    local file_count = 0

    for file_path, file_result in pairs(audit_results.file_metrics) do
        total_score = total_score + file_result.quality_score
        file_count = file_count + 1
    end

    return file_count > 0 and (total_score / file_count) or 0
end

-- 生成改进建议
function CodeQualityAuditor:generate_recommendations(audit_results)
    local recommendations = {}

    -- 分析最常见的问题类型
    local issue_counts = {}
    for _, issue in ipairs(audit_results.quality_issues) do
        issue_counts[issue.type] = (issue_counts[issue.type] or 0) + 1
    end

    -- 基于问题统计生成建议
    if issue_counts.long_function and issue_counts.long_function > 0 then
        table.insert(recommendations, {
            priority = "high",
            type = "refactoring",
            message = string.format("发现 %d 个过长函数，建议进行函数拆分", issue_counts.long_function),
            action = "将复杂函数拆分为更小的、单一职责的函数"
        })
    end

    if issue_counts.high_complexity and issue_counts.high_complexity > 0 then
        table.insert(recommendations, {
            priority = "high",
            type = "refactoring",
            message = string.format("发现 %d 个高复杂度函数，建议重构", issue_counts.high_complexity),
            action = "使用设计模式或算法优化来降低函数复杂度"
        })
    end

    if issue_counts.low_documentation and issue_counts.low_documentation > 0 then
        table.insert(recommendations, {
            priority = "medium",
            type = "documentation",
            message = "多个文件文档覆盖率不足，建议增加注释",
            action = "为函数和模块添加清晰的文档注释"
        })
    end

    if issue_counts.naming_convention and issue_counts.naming_convention > 5 then
        table.insert(recommendations, {
            priority = "low",
            type = "style",
            message = "存在命名规范不一致的情况",
            action = "统一使用项目命名规范（蛇形命名法、帕斯卡命名法）"
        })
    end

    -- 添加通用建议
    table.insert(recommendations, {
        priority = "medium",
        type = "process",
        message = "建议建立代码审查流程",
        action = "在代码提交前进行同行审查，提高代码质量"
    })

    table.insert(recommendations, {
        priority = "low",
        type = "tooling",
        message = "建议使用静态代码分析工具",
        action = "集成LuaLint等工具到CI/CD流程中"
    })

    return recommendations
end

-- 获取需要审计的文件列表
function CodeQualityAuditor:get_files_to_audit()
    -- 这里简化实现，实际应该使用glob匹配
    local files = {}

    -- 获取src目录下的所有lua文件
    local src_files = {
        "src/main.lua",
        "src/example_battle.lua",
        "src/battle/battle_manager.lua",
        "src/battle/battle_state.lua",
        "src/battle/combat_calculator.lua",
        "src/characters/character.lua",
        "src/characters/player.lua",
        "src/characters/enemy.lua",
        "src/characters/status_effects.lua",
        "src/skills/skill.lua",
        "src/skills/skill_manager.lua",
        "src/skills/skill_effects.lua",
        "src/skills/target_selector.lua",
        "src/items/item.lua",
        "src/items/item_manager.lua",
        "src/items/consumable.lua",
        "src/items/equipment.lua",
        "src/ai/ai_base.lua",
        "src/ai/tactical_ai.lua",
        "src/ai/decision_maker.lua",
        "src/ai/decision_tree.lua",
        "src/ai/ai_quality_assessor.lua",
        "src/ai/ai_debugger.lua",
        "src/ai/ai_parameter_tuner.lua",
        "src/ai/optimization_feedback_loop.lua",
        "src/utils/logger.lua",
        "src/utils/table_utils.lua",
        "src/utils/random.lua",
        "src/utils/event_system.lua",
        "src/utils/config_loader.lua",
        "src/utils/error_handler.lua",
        "src/utils/errors.lua",
        "src/utils/test_framework.lua",
        "src/utils/config_validator.lua",
        "src/utils/performance_monitor.lua",
        "src/config/system_config.lua",
        "src/config/battle_config.lua",
        "src/config/dynamic_config_manager.lua"
    }

    for _, file in ipairs(src_files) do
        table.insert(files, file)
    end

    return files
end

-- 读取文件内容
function CodeQualityAuditor:read_file(file_path)
    local file = io.open(file_path, "r")
    if not file then
        return nil
    end

    local content = file:read("*all")
    file:close()

    return content
end

-- 生成审计报告
function CodeQualityAuditor:generate_audit_report(audit_results)
    local report = {
        title = "Lua Battle System 代码质量审计报告",
        generated_at = os.date("%Y-%m-%d %H:%M:%S"),
        overall_score = audit_results.summary.overall_quality_score,
        grade = self:get_quality_grade(audit_results.summary.overall_quality_score),
        summary = audit_results.summary,
        quality_distribution = self:calculate_quality_distribution(audit_results),
        top_issues = self:get_top_issues(audit_results),
        recommendations = audit_results.recommendations
    }

    return report
end

-- 获取质量等级
function CodeQualityAuditor:get_quality_grade(score)
    if score >= 90 then return "A+ (优秀)" end
    if score >= 80 then return "A (良好)" end
    if score >= 70 then return "B (中等)" end
    if score >= 60 then return "C (需要改进)" end
    return "D (不合格)"
end

-- 计算质量分布
function CodeQualityAuditor:calculate_quality_distribution(audit_results)
    local distribution = {
        excellent = 0,  -- 90+
        good = 0,       -- 80-89
        fair = 0,       -- 70-79
        poor = 0        -- <70
    }

    for _, file_result in pairs(audit_results.file_metrics) do
        if file_result.quality_score >= 90 then
            distribution.excellent = distribution.excellent + 1
        elseif file_result.quality_score >= 80 then
            distribution.good = distribution.good + 1
        elseif file_result.quality_score >= 70 then
            distribution.fair = distribution.fair + 1
        else
            distribution.poor = distribution.poor + 1
        end
    end

    return distribution
end

-- 获取主要问题
function CodeQualityAuditor:get_top_issues(audit_results)
    local issue_counts = {}

    for _, issue in ipairs(audit_results.quality_issues) do
        issue_counts[issue.type] = (issue_counts[issue.type] or 0) + 1
    end

    local top_issues = {}
    for issue_type, count in pairs(issue_counts) do
        table.insert(top_issues, {
            type = issue_type,
            count = count,
            description = self:get_issue_description(issue_type)
        })
    end

    -- 按数量排序
    table.sort(top_issues, function(a, b) return a.count > b.count end)

    return top_issues
end

-- 获取问题描述
function CodeQualityAuditor:get_issue_description(issue_type)
    local descriptions = {
        long_function = "函数过长",
        high_complexity = "函数复杂度过高",
        missing_module_doc = "缺少模块文档",
        low_documentation = "文档覆盖率低",
        naming_convention = "命名不规范",
        formatting = "格式问题",
        global_variable = "使用全局变量",
        unused_variable = "未使用变量",
        debug_code = "调试代码残留",
        todo_comment = "有待办事项",
        line_length = "行过长"
    }

    return descriptions[issue_type] or issue_type
end

-- 导出审计结果
function CodeQualityAuditor:export_results(audit_results, format)
    format = format or "text"

    if format == "json" then
        return self:export_json(audit_results)
    elseif format == "html" then
        return self:export_html(audit_results)
    else
        return self:export_text(audit_results)
    end
end

-- 导出文本格式
function CodeQualityAuditor:export_text(audit_results)
    local report_lines = {}

    table.insert(report_lines, "═══════════════════════════════════════════════════════════════")
    table.insert(report_lines, "           Lua Battle System 代码质量审计报告")
    table.insert(report_lines, "═══════════════════════════════════════════════════════════════")
    table.insert(report_lines, "")
    table.insert(report_lines, string.format("生成时间: %s", audit_results.summary.audit_timestamp))
    table.insert(report_lines, string.format("总体评分: %.1f (%s)",
        audit_results.summary.overall_quality_score,
        self:get_quality_grade(audit_results.summary.overall_quality_score)))
    table.insert(report_lines, "")

    -- 审计摘要
    table.insert(report_lines, "📊 审计摘要")
    table.insert(report_lines, "───────────────────────────────────────────────────────────")
    table.insert(report_lines, string.format("审计文件总数: %d", audit_results.summary.total_files))
    table.insert(report_lines, string.format("通过文件数量: %d", audit_results.summary.files_passed))
    table.insert(report_lines, string.format("失败文件数量: %d", audit_results.summary.files_failed))
    table.insert(report_lines, string.format("发现问题总数: %d", #audit_results.quality_issues))
    table.insert(report_lines, string.format("通过率: %.1f%%",
        (audit_results.summary.files_passed / audit_results.summary.total_files) * 100))
    table.insert(report_lines, "")

    -- 质量分布
    local dist = self:calculate_quality_distribution(audit_results)
    table.insert(report_lines, "📈 质量分布")
    table.insert(report_lines, "───────────────────────────────────────────────────────────")
    table.insert(report_lines, string.format("优秀 (90+分): %d 个文件", dist.excellent))
    table.insert(report_lines, string.format("良好 (80-89分): %d 个文件", dist.good))
    table.insert(report_lines, string.format("中等 (70-79分): %d 个文件", dist.fair))
    table.insert(report_lines, string.format("需要改进 (<70分): %d 个文件", dist.poor))
    table.insert(report_lines, "")

    -- 主要问题
    local top_issues = self:get_top_issues(audit_results)
    if #top_issues > 0 then
        table.insert(report_lines, "⚠️  主要问题")
        table.insert(report_lines, "───────────────────────────────────────────────────────────")
        for i, issue in ipairs(top_issues) do
            if i <= 5 then  -- 只显示前5个
                table.insert(report_lines, string.format("• %s: %d 次", issue.description, issue.count))
            end
        end
        table.insert(report_lines, "")
    end

    -- 改进建议
    if #audit_results.recommendations > 0 then
        table.insert(report_lines, "💡 改进建议")
        table.insert(report_lines, "───────────────────────────────────────────────────────────")
        for _, rec in ipairs(audit_results.recommendations) do
            table.insert(report_lines, string.format("• [%s] %s", rec.priority, rec.message))
        end
        table.insert(report_lines, "")
    end

    table.insert(report_lines, "═══════════════════════════════════════════════════════════════")

    return table.concat(report_lines, "\n")
end

-- 创建新实例
function CodeQualityAuditor:new(config)
    local instance = {
        config = TableUtils.deep_copy(self.config),
        state = {}
    }

    setmetatable(instance, {__index = self})

    return instance
end

return CodeQualityAuditor